package com.jujia.tmall.ui;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;

import com.elune.ui.ConnectionToast;
import com.jujia.tmall.activity.R;


/**
 *  不支持输入表情符号的可显示隐藏输入密码EditTextView
 * Created by wenhaiju on 2016/12/6.
 */
public class PassSeeEditTextNoEmoji extends EditText implements OnFocusChangeListener,
        TextWatcher {
	/**
	 * 删除按钮的引用
	 */
	private Drawable mClearDrawable;
	private int mark = 0;

	private int cursorPos;
	private String inputAfterText;
	private boolean resetText;
	private Context mContext;

	public PassSeeEditTextNoEmoji(Context context) {
		this(context, null);
	}

	public PassSeeEditTextNoEmoji(Context context, AttributeSet attrs) {
		// 这里构造方法也很重要，不加这个很多属性不能再XML里面定义
		this(context, attrs, android.R.attr.editTextStyle);
	}

	public PassSeeEditTextNoEmoji(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.mContext = context;
		init();
	}

	private void init() {
		// 获取EditText的DrawableRight,假如没有设置我们就使用默认的图片
		mClearDrawable = getCompoundDrawables()[2];
		if (mClearDrawable == null) {
			mClearDrawable = getResources().getDrawable(
					R.mipmap.password_invisible);
		}
		mClearDrawable.setBounds(0, 0,
				(int) getResources().getDimension(R.dimen.x20),
				(int) getResources().getDimension(R.dimen.x20));
		setClearIconVisible(false);
		setOnFocusChangeListener(this);
		addTextChangedListener(this);
	}

	/**
	 * 因为我们不能直接给EditText设置点击事件，所以我们用记住我们按下的位置来模拟点击事件 当我们按下的位置 在 EditText的宽度 -
	 * 图标到控件右边的间距 - 图标的宽度 和 EditText的宽度 - 图标到控件右边的间距之间我们就算点击了图标，竖直方向没有考虑
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {

		if (getCompoundDrawables()[2] != null) {
			if (event.getAction() == MotionEvent.ACTION_UP) {
				boolean touchable = event.getX() > (getWidth()
						- getPaddingRight() - mClearDrawable
							.getIntrinsicWidth())
						&& (event.getX() < ((getWidth() - getPaddingRight())));

				if (touchable) {
					if (mark % 2 == 0) {
						mClearDrawable = getResources().getDrawable(
								R.mipmap.password_visible);
						setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
						setSelection(getText().length());
					} else {
						mClearDrawable = getResources().getDrawable(
								R.mipmap.password_invisible);
						setInputType(InputType.TYPE_CLASS_TEXT
								| InputType.TYPE_TEXT_VARIATION_PASSWORD);
						setSelection(getText().length());
					}
					mClearDrawable.setBounds(0, 0, (int) getResources()
							.getDimension(R.dimen.x20), (int) getResources()
							.getDimension(R.dimen.x20));
					setClearIconVisible(true);
					this.invalidate();
					mark++;

					// this.setText("");
				}
			}
		}

		return super.onTouchEvent(event);
	}

	/**
	 * 当ClearEditText焦点发生变化的时候，判断里面字符串长度设置清除图标的显示与隐藏
	 */
	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		if (hasFocus) {
			setClearIconVisible(getText().length() > 0);
		} else {
			setClearIconVisible(false);
		}
	}

	/**
	 * 设置清除图标的显示与隐藏，调用setCompoundDrawables为EditText绘制上去
	 * 
	 * @param visible
	 */
	protected void setClearIconVisible(boolean visible) {
		Drawable right = visible ? mClearDrawable : null;
		setCompoundDrawables(getCompoundDrawables()[0],
				getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
	}

	int num = 0;// 判断点击软键盘上表情符号的次数 add by wenhaiju
	/**
	 * 当输入框里面内容发生变化的时候回调的方法
	 */
	@Override
	public void onTextChanged(CharSequence s, int start, int before,
                              int count) {
		if (!resetText) {
			if (before == 0) {
				CharSequence input = s.subSequence(cursorPos, cursorPos
						+ count);
				if (containsEmoji(input.toString())) {
					resetText = true;
					num += 1;
					if (num < 2) {
						ConnectionToast.ToastShowBottom(mContext, "不支持输入表情符号" );
					}

					setText(inputAfterText);
					CharSequence text = getText();
					if (text instanceof Spannable) {
						Spannable spanText = (Spannable) text;
						Selection.setSelection(spanText,
								spanText.length());
					}
					setClearIconVisible(inputAfterText.length() > 0);
				}
				setClearIconVisible(s.length() > 0);

			}
		} else {
			resetText = false;
			setClearIconVisible(s.length() > 0);
		}

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {
		if (!resetText) {
			cursorPos = getSelectionEnd();
			inputAfterText = s.toString();
		}
	}

	@Override
	public void afterTextChanged(Editable s) {

	}

	public static boolean containsEmoji(String source) {
		int len = source.length();
		for (int i = 0; i < len; i++) {
			char codePoint = source.charAt(i);
			if (!isEmojiCharacter(codePoint)) {
				return true;
			}
		}
		return false;
	}

	private static boolean isEmojiCharacter(char codePoint) {
		int b = codePoint;
		Log.i("Test", Integer.toHexString(b));
		return (codePoint == 0x0)
				|| (codePoint == 0x9)
				|| (codePoint == 0xA)
				|| (codePoint == 0xD)
				|| ((codePoint >= 0x20) && (codePoint <= 0xD7FF) && (codePoint != 0x263a))
				|| ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
				|| ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
	}

	/**
	 * 设置晃动动画
	 */
	public void setShakeAnimation() {
		this.setAnimation(shakeAnimation(5));
	}

	/**
	 * 晃动动画
	 * 
	 * @param counts
	 *            1秒钟晃动多少下
	 * @return
	 */
	public static Animation shakeAnimation(int counts) {
		Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
		translateAnimation.setInterpolator(new CycleInterpolator(counts));
		translateAnimation.setDuration(1000);
		return translateAnimation;
	}

}
